//
//  NSObject+Model.m
//  CaiYun
//
//  Created by 今日信息科技 on 2017/8/17.
//  Copyright © 2017年 今日信息科技. All rights reserved.
//

#import "NSObject+Model.h"
@implementation NSObject (Model)
- (instancetype)initWithDict:(NSDictionary *)dict{
    self = [self init];
    if (self) {
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

+ (instancetype)getModel:(NSDictionary *)dict{
    if ([dict count] > [[self propertiesArray] count])
        return [self model:dict];
    else
        return [[self alloc] initWithDict:dict];
}

+ (instancetype)model:(NSDictionary *)dict{
    id obj = [self new];
    for (NSString *property in [self propertiesArray]) {
        
        id value = [self ergodic:dict missingKey:property];//遍历字典是否包含某个属性，如包含，则返回key为某个属性的value
        [obj setValue:value forKey:property];
    }
    return obj;
}

//遍历字典，查看keys是否包含某个属性，如果不包含，则递归，直到找到包含的某个属性的键值对，如果都没有则抛出异常
+ (instancetype)ergodic:(NSDictionary *)dict missingKey:(NSString *)property {
    
    NSArray *keys = [dict allKeys];
    
    if ([keys containsObject:property])
        return dict[property];
    else{
        for (int i = 0; i < keys.count; i ++ ) {
            id data = dict[keys[i]];
            if ([data isKindOfClass:[NSDictionary class]])
                return [self ergodic:data missingKey:property];
        }
    }
    return nil;
}


+ (NSArray *)propertiesArray{
    unsigned int count = 0;//属性个数
    NSMutableArray *arr = [NSMutableArray array];//存储属性名称的数组
    objc_property_t *propertyList = class_copyPropertyList([self class], &count);//获取model的属性数组
    for (int i = 0; i< count; i++) {//遍历属性数组
        objc_property_t property = propertyList[i];//获取属性
        const char *cName = property_getName(property);//获取属性名称
        NSString *name = [[NSString alloc]initWithUTF8String:cName];//转码
        [arr addObject:name];//存储到数组中
    }
    free(propertyList);//释放属性数组
    return arr.copy;
}


@end
